import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    // 菜单
    menu: [],
    // 权限
    perms: [],
  },
  mutations: {
    setMenu(state, menu){
      state.menu = menu;
    },

    setPerms(state, perms){
      state.perms = perms;
    },

    resetState(state){
      state.menu = [];
      state.perms = [];
    },
  },
  actions: {
    /**
     * 重置数据
     * @param context
     */
    resetState(context){
      context.commit('resetState');
    },
    /**
     * 初始化导航
     * @param context
     * @returns {Promise<unknown>}
     */
    initMenu(context){
      return new Promise( (resolve) => {
        let nav = window.storage.getItem(window.storage.key.nav_key);
        if(nav){
          context.commit('setMenu', nav.menuList);
          context.commit('setPerms', nav.permissions);
          resolve();
        }
        // 判断是否已经登录开始请求导航列表
        if(window.storage.getItem(window.storage.key.token)){
          window.api.get("sp/sys/menu/nav", {
          }).then((res)=>{
            if(res.data.code === 0){
              let nav = res.data;
              context.commit('setMenu', nav.menuList);
              context.commit('setPerms', nav.permissions);
              window.storage.setItem(window.storage.key.nav_key, nav);
              resolve();
            }else{
              context.commit('setMenu', []);
              context.commit('setPerms', []);
              resolve();
            }
          });
        }
      });
    },
  },
  modules: {
  }
});
